from http import cookiejar
import re,requests,time

session=requests.session()#在会话中保留状态，保持cookie等
session.cookies=cookiejar.LWPCookieJar(filename="cookies.txt")#写入cookie
try:
    session.cookies.load(ignore_discard=True)
except:
    print('cookis未能加载')

agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
header = {
    "HOST":"www.zhihu.com",
    "Referer":"https://www.zhihu.com/signup",
    "User-Agent":agent
}
#测试页面
def get_index():
    res = session.get("https://www.zhihu.com/signup", headers=header)
    with open("index.html","wb") as f:
        f.write(res.text.encode("utf-8"))
    print("ok")
#分析页面
def get_xsrf():
    res = session.get("https://www.zhihu.com/signup", headers=header)
    print(res.text)
    exit()
#模拟登陆（目前是失败的，解决办法：先真实登陆然后将cookie文件导出，然后再访问页面的时候直接加载cookie文件）
def zhihu_login():
    time_int=int(time.time()*1000)
    post_url="https://www.zhihu.com/api/v3/oauth/sign_in"
    post_data={#http://blog.csdn.net/yu12377/article/details/77188895
        #模拟multipart/form-data方式提交
        "username": "+8618764285761",
        "password": "bangde007",
        "client_id":"c3cef7c66a1843f8b3a9e6a1e3160e20",
        "grant_type":"password",
        "timestamp":str(time_int),
        "source":"com.zhihu.web",
        "signature":"e01ed2d28d01cd789be5d1c008f98054c9ed5e14",
        "ref_source":"inbox",
        "captcha":"",
        "utm_source":"",
        "lang":"en",
    }
    res_text = session.post(post_url, files=post_data,headers=header)
    session.cookies.save()

#通过个人中心返回状态码判断是否已经登陆成功
def is_login():
    url="https://www.zhihu.com/settings/profile"
    #请求后直接返回状态码
    response=session.get(url,headers=header,allow_redirects=False)#allow_redirects参数防止请求失败发生重定向
    if response.status_code !=200:
        return False
    else:
        return True
is_login()
